package x.ovo.wechat.bot;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.common.entity.event.MessageEvent;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.event.Event;
import x.ovo.wechat.bot.common.event.EventListener;
import x.ovo.wechat.bot.common.util.WechatUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j(topic = "舔狗日记")
public class TiangouListener extends EventListener<MessageEvent<TextMessage>> {

    private static final String URL = "https://api.qqsuu.cn/api/dm-tiangou";
    public static final Pattern PATTERN = Pattern.compile("\"content\":\\s?\"(.*)\"");

    @Override
    public boolean support(Event<?> event) {
        return event instanceof MessageEvent
                && event.getSource() instanceof TextMessage
                && ((MessageEvent<?>) event).getContent().contains("舔狗");
    }

    @Override
    public void onEvent(MessageEvent<TextMessage> event) {
        String userName = event.getSource().getFromUser().getUserName();
        try {
            Matcher matcher = PATTERN.matcher(HttpUtil.get(URL));
            if (matcher.find()) {
                String content = WechatUtil.format(matcher.group(1));
                this.context.getApi().sendText(userName, content);
                return;
            }
            this.context.getApi().sendText(userName, "你自己舔吧，我不想舔了");
        } catch (Exception e) {
            log.error("获取舔狗日记失败", e);
            this.context.getApi().sendText(userName, "舔不动，你自己舔");
        }
    }
}
